<template>
  <PageHeaderWrapper>
    <a-card class="invoicing-theme">
      <a-row>
        <a-col :span="7">
          用户名：
          <a-input v-model="name" placeholder="请输入" class="input-width"/>
        </a-col>
        <a-col :span="7">
          角色：
          <a-select placeholder="请选择" style="width: 70%" v-model="role">
            <a-spin slot="notFoundContent" size="small" />
            <a-select-option v-for="item in roleList" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          状态：
          <a-select placeholder="请选择" style="width: 70%" v-model="status">
            <a-spin slot="notFoundContent" size="small" />
            <a-select-option value="在线">在线</a-select-option>
            <a-select-option value="离线">离线</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="2">
          <a-button type="primary" icon="search" @click="handleRefreshAndSearch">
            搜索
          </a-button>
        </a-col>
        <a-col :span="1">
          <a-button type="primary" :disabled="disabled" icon="sync" @click="resetSearch">
            重置
          </a-button>
        </a-col>
      </a-row>
    </a-card>
    <a-card>
      <a-row class="table-operations">
        <a-col :span="2">
          <a-button type="primary" icon="plus" @click="showModal('添加用户')">
            添加
          </a-button>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" icon="reload" @click="handleRefreshAndSearch">
            刷新
          </a-button>
        </a-col>
      </a-row>
      <a-alert showIcon style="margin-bottom: 10px">
        <template slot="message">
          <span style="margin-right: 12px">已选择: <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项</span>
          <a style="margin-left: 20px" @click="deleteBatch" v-if="selectedRowKeys.length > 0">批量删除</a>
          <a style="margin-left: 20px" @click="clearSelected" v-if="selectedRowKeys.length > 0">清空</a>
        </template>
      </a-alert>
      <a-table
        :columns="columns"
        :data-source="userList"
        rowKey="id"
        :pagination="pagination"
        :loading="tableIsLoading"
        @change="handleTableChange"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: handleSelectChange }"
      >
        <template slot="operation" slot-scope="text, record">
          <span class="delete">
            <a-popconfirm
              title="确定要删除该用户吗？"
              ok-text="Yes"
              cancel-text="No"
              @confirm="deleteConfirm(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>
          </span>
          <a @click="edit(record)">编辑</a>
        </template>
      </a-table>
      <a-modal
        :title="title"
        width="420px"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
          <a-form-item label="用户名" has-feedback>
            <a-input
              v-decorator="['username', {
                rules: [{ required: true, message: '请输入用户名!' }],
                initialValue: defaultUserName
              }]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="密码">
            <a-input-password
              v-decorator="['password', {
                rules: [{ required: true, message: '请输入密码！' }],
                initialValue: defaultPassWord
              }]"
              placeholder="******"
            />
          </a-form-item>
          <a-form-item label="角色">
            <a-select
              v-decorator="['role', {
                rules: [{ required: true, message: '请选择角色!' }],
                initialValue: defaultRole
              }]"
              placeholder="请选择"
            >
              <a-select-option v-for="item in roleList" :value="item" :key="item">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </PageHeaderWrapper>
</template>

<script>
import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import { getUserList, deleteUser, addUser, editUser, roleList } from '@/api/userManage'
const defaultPagination = {
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20'],
  showTotal: total => `总共 ${total} 条数据`
}
export default {
  name: 'UserManage',
  components: { PageHeaderWrapper },
  mounted () {
    this.getUserInfo()
    this.getRoleList()
  },
  computed: {
    columns () {
      const columns = [
        {
          title: '用户名',
          dataIndex: 'username',
          align: 'center',
          key: 'username'
        },
        {
          title: '状态',
          dataIndex: 'onlineStatus',
          align: 'center',
          key: 'onlineStatus',
          customRender: (text, record, index) => {
            if (text === 1) {
              return <a-badge status="success" text="在线"/>
            } else {
              return <a-badge status="error" text="离线" />
            }
          }
        },
        {
          title: '角色',
          dataIndex: 'role',
          align: 'center',
          key: 'role'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center',
          key: 'createTime'
        },
        {
          title: '上次登录时间',
          dataIndex: 'lastLoginTime',
          align: 'center',
          key: 'lastLoginTime',
          sorter: true
        },
        {
          title: '操作',
          align: 'center',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ]
      return columns
    },
    disabled () {
      return !this.name && !this.role && !this.status
    }
  },
  data () {
    return {
      pagination: defaultPagination,
      sorter: null,
      tableIsLoading: false,
      userList: [],

      selectedRowKeys: [],
      name: null,
      role: null,
      status: null,
      roleList: [],

      // modal
      title: '',
      visible: false,
      defaultUserName: '',
      defaultRole: '',
      defaultPassWord: '',
      userId: '',
      confirmLoading: false,
      form: this.$form.createForm(this, { name: 'coordinated' })
    }
  },
  methods: {
    getUserInfo () {
      const _this = this
      const sorter = this.sorter || {}
      this.tableIsLoading = true
      getUserList({
        page: _this.pagination.current,
        pageSize: _this.pagination.pageSize,
        order: sorter.order,
        name: _this.name,
        role: _this.role,
        status: _this.status
      })
        .then(function (res) {
          _this.userList = res.data.list
          _this.pagination.total = res.data.total
        }).catch(function (err) {
          _this.$message.error(err.response.data.msg)
        }).finally(function () {
          _this.tableIsLoading = false
        })
    },
    getRoleList () {
      const _this = this
      roleList().then(res => {
        _this.roleList = res.data.roleNameList
      }).catch(err => {
        _this.$message.error(err.response.data.msg)
      })
    },
    resetSearch () {
      this.name = null
      this.role = null
      this.status = null
    },
    handleRefreshAndSearch () {
      this.pagination.current = 1
      this.getUserInfo()
    },
    handleTableChange (pagination, filters, sorter) {
      // console.log('表格变化', pagination, sorter)
      this.pagination = pagination
      this.sorter = sorter
      this.getUserInfo()
    },
    deleteConfirm (id) {
      const _this = this
      deleteUser(id)
      .then(function (res) {
        _this.$message.success('删除用户成功')
        _this.handleRefreshAndSearch()
      })
      .catch(function (err) {
        _this.$message.error(err.response.data.msg)
      })
    },
    edit (user) {
      this.title = '编辑用户'
      this.userId = user.id
      this.defaultUserName = user.username
      this.defaultRole = user.role
      this.defaultPassWord = user.password
      this.visible = true
    },
    showModal (value) {
      this.title = value
      this.visible = true
    },
    handleOk (e) {
      this.confirmLoading = true
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.title === '添加用户') {
            addUser({
              username: values.username,
              password: values.password,
              role: values.role
            })
            .then(function (res) {
              _this.confirmLoading = false
              _this.handleCancel()
              _this.handleRefreshAndSearch()
              _this.$message.success('添加用户成功')
            })
            .catch(function (err) {
              _this.$message.error(err.response.data.msg)
              _this.confirmLoading = false
            })
          } else if (this.title === '编辑用户') {
            editUser({
              id: _this.userId,
              username: values.username,
              password: values.password,
              role: values.role
            })
            .then(function (res) {
              _this.confirmLoading = false
              _this.visible = false
              _this.handleRefreshAndSearch()
              _this.$message.success('修改用户成功')
            })
            .catch(function (err) {
              _this.$message.error(err.response.data.msg)
              _this.confirmLoading = false
            })
          }
        } else {
          _this.confirmLoading = false
        }
      })
    },
    handleCancel (e) {
      this.form.resetFields()
      this.defaultUserName = ''
      this.defaultRole = ''
      this.defaultPassWord = ''
      this.visible = false
    },
    handleSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    deleteBatch () {
      this.$message.info('暂未开发')
    },
    clearSelected () {
      this.handleSelectChange([])
    }
  }
}
</script>

<style lang="less" scoped>
.input-width {
  width: 70%;
}
.table-operations {
  margin-bottom: 10px;
}
.delete {
  margin-right: 10px;
}
</style>
